package com.penghaisoft.microwms.material.web.outwarehouse.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.ws.rs.core.MediaType;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.penghaisoft.microwms.common.Constant;
import com.penghaisoft.microwms.common.controller.BaseController;
import com.penghaisoft.microwms.common.data.model.RawRequisition;
import com.penghaisoft.microwms.common.data.model.RawRequisitionSn;
import com.penghaisoft.microwms.common.dto.HandResp;
import com.penghaisoft.microwms.common.dto.RawOrderOutDto;
import com.penghaisoft.microwms.common.dto.RawRequisitionMesDto;
import com.penghaisoft.microwms.common.dto.TransResult;
import com.penghaisoft.microwms.common.page.Pager;
import com.penghaisoft.microwms.common.service.IMesInterfaceService;
import com.penghaisoft.microwms.common.service.MesProperties;
import com.penghaisoft.microwms.material.web.outwarehouse.service.OutWhRawService;

import lombok.extern.slf4j.Slf4j;

/**
 * Created by 王治国 on 2018/5/17.
 * 原材料出库查询
 */
@RestController
@RequestMapping(value = "raw/rawOutWh")
@Slf4j
public class OutWhRawController extends BaseController {

    @Autowired
    private OutWhRawService outWhRawService;
    
    @Resource
	private MesProperties mesProperties;
    
    @Autowired
	private IMesInterfaceService mesInterfaceService;

    @PostMapping("list")
    public TransResult findAll(@RequestParam(name = "page", defaultValue = "1") int page,
                               @RequestParam(name = "rows", defaultValue = "10") int rows, RawRequisition rawRequisition) {
        Pager<RawRequisition> result = outWhRawService.findAll(page, rows, rawRequisition);
        
        String sumInfo = result.getOrder();
		if (sumInfo != null && sumInfo.length() > 0) {
			result.setOrder(sumInfo);
		}
		
        return success(result);
    }
    
    /** 
     * @Title findList
     * @Description 根据领料单号查询数据
     * @author luoteng
     * @date 2018年7月3日:下午4:32:02
     * @param rawRequisition
     * @return TransResult
     */
    @PostMapping("list/info")
    public TransResult findList(RawRequisition rawRequisition) {
    	TransResult result = new TransResult();
    	result.setCode(Constant.SUCCESS);
    	rawRequisition.setActiveFlag("1");
        List<RawRequisition> list = outWhRawService.findList(rawRequisition);
        if(list != null && !list.isEmpty()){
        	RawRequisition tmp = list.get(0);
        	tmp.setCreateBy(getUserName());
        	tmp.setGmtCreate(new Date());
        }
        result.setList(list);
        return result;
    }
    
    /** 
     * @Title findList
     * @Description 根据领料单号查询匹配信息
     * @author luoteng
     * @date 2018年7月3日:下午4:32:02
     * @param rawRequisition
     * @return TransResult
     */
    @PostMapping("list/scan/info")
    public TransResult findScanList(RawRequisitionSn rawRequisitionSn) {
    	TransResult result = new TransResult();
    	result.setCode(Constant.SUCCESS);
//    	rawRequisitionSn.setModelType(Constant.MODEL_PE);
    	rawRequisitionSn.setModelTypeNotEqualList(Constant.PE_LIST);
        List<RawRequisitionSn> list = outWhRawService.queryScanInfo(rawRequisitionSn);
        if(list != null && !list.isEmpty()){
        	RawRequisitionSn tmp = list.get(0);
        	tmp.setCreateBy(getUserName());
        	tmp.setGmtCreate(new Date());
        }
        result.setList(list);
        return result;
    }
    
    /** 
     * @Title findListByRequestionNo
     * @Description 根据领料单号查询列表
     * @author luoteng
     * @date 2018年7月3日:下午4:32:02
     * @param page
     * @param rows
     * @param rawRequisitionSn
     * @return TransResult
     */
    @PostMapping("list/requisitionNo")
    public TransResult findListByRequestionNo(@RequestParam(name = "page", defaultValue = "1") int page,
                               @RequestParam(name = "rows", defaultValue = "10") int rows, RawRequisitionSn rawRequisitionSn) {
    	rawRequisitionSn.setActiveFlag("1");
        Pager<RawRequisitionSn> result = outWhRawService.findListByRequestionNo(page, rows, rawRequisitionSn);
        return success(result);
    }
    
    /**  
     * @Title: confirmRequisitionNo
     * @Description:   辅料出库确认
     * @author Lengxf  
     * @date 2019年2月25日    
     */  
    @PostMapping("confirm/requisitionNo")
    public TransResult confirmRequisitionNo(RawRequisition rawRequisition){
    	TransResult result  = new TransResult();
    	boolean flag = false;
    	result = outWhRawService.confirmRequisitionNo(rawRequisition);
    	
    	if(Constant.SUCCESS.equals(result.getCode())){
    		flag = true;
    	}
  
    	if(flag){
    		
    		String url = mesProperties.getUrl() + "/imes-provider/productplan/follow/ordersplit/materialin";
    		
    		RawRequisition entity = outWhRawService.queryByRequestionId(rawRequisition);
    		
    		RawRequisitionSn rawRequisitionSn = new RawRequisitionSn();
        	rawRequisitionSn.setRequisitionId(rawRequisition.getRequisitionId());
        	List<RawRequisitionSn> snList = outWhRawService.queryRequisitionById(rawRequisitionSn);

    		List<RawRequisitionMesDto> mesList = new ArrayList<RawRequisitionMesDto>();
    		
    		RawRequisitionMesDto mesOb = new RawRequisitionMesDto();
        	mesOb.setMaterialId(" ");
        	mesOb.setMaterialCode(entity.getModel());
        	mesOb.setMaterialType(entity.getModelType());

        	if(snList != null & snList.size() > 0){
        		RawRequisitionSn sn = snList.get(0);
        		//当进行修改数据时，与原数据进行做差，返回差值
        		if(rawRequisition.getRealAmount() == null || "".equals(rawRequisition.getRealAmount())){
        			rawRequisition.setRealAmount(BigDecimal.ZERO);
        		}
        		BigDecimal zengliang = rawRequisition.getRealAmount().subtract(sn.getAmount());
        		mesOb.setQuantity(zengliang);
        	}else{
        		mesOb.setQuantity(rawRequisition.getRealAmount());
        	}
        	
        	mesOb.setMeasureUnit(entity.getUnit());
        	mesList.add(mesOb);
        	
        	JSONObject ob = new JSONObject();
            ob.put("receiptNo", entity.getRequisitionNo());
            ob.put("salesCode", entity.getContractNo());
            //领料类型 1 普通料（钢管、pe管、管件） 2 辅料
            ob.put("type", "2");
            ob.put("materialList", mesList);
            
            //调mes新增接口
    		HandResp handResp = mesInterfaceService.publicWSResp(url, MediaType.APPLICATION_JSON_TYPE, ob.toJSONString());
    		
    		if(handResp.getCode() != null && handResp.getCode().equals("0")){
    			result.setCode(handResp.getCode());
    			result.setMsg(handResp.getMsg());
    	        return result;
    		}{
    			//返回成功时，更新wms数据库
    			outWhRawService.confirmRequisitionNoUpdate(rawRequisition, getLoginName());
    		}
	    		

    	}

    	
    	
    	return result;
    }
    
    /**  
     * @Title: getIdRequistionId
     * @Description:  查询单条数据 
     * @author Lengxf  
     * @date 2019年2月25日    
     */  
    @GetMapping("get/id/{requisitionId}")
    public TransResult getIdRequistionId(@PathVariable("requisitionId") String requisitionId ){
    	TransResult result = new TransResult();
    	result.setCode(Constant.SUCCESS);
    	RawRequisition rawRequisition = new RawRequisition();
    	rawRequisition.setRequisitionId(Integer.parseInt(requisitionId));
    	RawRequisition entity = outWhRawService.queryByRequestionId(rawRequisition);
        if(entity.getRequisitionStatus() != "0" && entity.getRequisitionStatus() != null){
        	result.setMsg("该领料单当前状态无法进行领料出库操作");
        	result.setCode(Constant.FAIL);
        	return result;
        }
    	result.setData(entity);
    	return result;
    }
    
    /**  
     * @Title: closeRequisitionNo
     * @Description:   关闭领料单
     * @author Lengxf  
     * @date 2019年2月26日    
     */  
    @PostMapping("close/requisitionNo")
    public TransResult closeRequisitionNo(RawRequisition rawRequisition){
    	TransResult result = new TransResult();
    	result = outWhRawService.closeRequestionNo(rawRequisition, getLoginName());
    	return result;
    }
    
    /**  
     * @Title: isCheckOkRequisitionNo
     * @Description:   操作前校验该领料单是否符合修改逻辑
     * @author Lengxf  
     * @date 2019年2月28日    
     */  
    @PostMapping("isCheckOk/requisitionNo")
    public TransResult isCheckOkRequisitionNo(RawRequisition rawRequisition){
    	TransResult result = new TransResult();
    	result = outWhRawService.confirmRequisitionNo(rawRequisition);
    	return result;
    }

}
